﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CL_Sales
{
    public class RequestBatchCLSalesData
    {
        private readonly HttpClient client;
        private readonly int waittime;        
        private string P3;       
        private string P9;       

        public RequestBatchCLSalesData(HttpClient client, int waittime, string p3, string p9)
        {
            this.client = client;
            this.waittime = waittime;            
            this.P3 = p3;            
            this.P9 = p9;            
        }

        public async Task<HttpResponseMessage> GetSalesData(DateTime start, DateTime end)
        {
            //step1
            string datestr = "2 ";
            datestr = datestr + start.ToString("yyyyMMdd");
            datestr = datestr + " ";
            datestr = datestr + end.ToString("yyyyMMdd");
            HttpResponseMessage response = await client.SendAsync(RequestSalesStep1(datestr));
            await Task.Delay(waittime);
            response.EnsureSuccessStatusCode();
            var responseContent = await response.Content.ReadAsStringAsync();
            //step2循环最多20次
            for (int i = 0; i < 20; i++)
            {
                await Task.Delay(waittime);
                response = await client.SendAsync(RequestSalesStep2(datestr));
                await Task.Delay(waittime);
                response.EnsureSuccessStatusCode();
                responseContent = await response.Content.ReadAsStringAsync();
                if (!responseContent.Contains("Searching... To cancel, click"))
                {
                    break;
                }
            }
            //获取下载准备需要的post数据
            string pattern = @"idPrintLinksMenu([^'']+)";
            Match match = Regex.Match(responseContent, pattern);
            string viewid = match.Groups[1].Value;
            pattern = @"sid=""([^""]+)""";
            match = Regex.Match(responseContent, pattern);
            string sid = match.Groups[1].Value;
            pattern = @"ViewState=([^\&""]+)";
            match = Regex.Match(responseContent, pattern);
            string viewstate = match.Groups[1].Value;
            pattern = @"<nqw[^>]*>(.*?)</nqw>";
            match = Regex.Match(responseContent, pattern);
            string xml = match.Groups[1].Value;
            xml = xml.Replace("\\u003c", "<");
            xml = xml.Replace("\\\"", "\"");
            pattern = @"<sawst:stateRef>(.*?)</sawst:stateRef>";
            match = Regex.Match(xml, pattern, RegexOptions.Singleline);
            xml = match.Groups[1].Value;
            response = await client.SendAsync(RequestSalesStep3(viewid, sid, viewstate, xml));
            await Task.Delay(1500);
            response.EnsureSuccessStatusCode();
            responseContent = await response.Content.ReadAsStringAsync();
            //下载数据文件
            pattern = @"obips\.download\.downloadStatus\('([^']*)'";
            match = Regex.Match(responseContent, pattern);
            string downloadStatus = match.Groups[1].Value;
            response = await client.SendAsync(RequestSalesStep4(downloadStatus));
            response.EnsureSuccessStatusCode();
            return response;
        }

        /// <summary>
        /// 进入登录数据库界面
        /// </summary>
        private HttpRequestMessage RequestSalesStep1(string dateStr)
        {            
            var message = new HttpRequestMessage(HttpMethod.Post, "https://biee.mcdonalds.cn/analytics/saw.dll?PortalPages&PortalPath=/shared/Dashboard/_portal/Daily%20Sales&Action=Navigate&Options=dfr&syndicate=siebel&Page=R07.Daily%20Sales%20Rpt%20by%20Period%20And%20Store");           
            message.Content = new FormUrlEncodedContent(new[]
           {
                new KeyValuePair<string, string>("NQUser","Store"),
                new KeyValuePair<string, string>("NQPassword","Pass1234"),
                new KeyValuePair<string, string>("P0","4"),
                new KeyValuePair<string, string>("P1","eq"),
                new KeyValuePair<string, string>("P2","\"Operation\".\"Store Key\""),
                new KeyValuePair<string, string>("P3",P3),                
                new KeyValuePair<string, string>("P4","bet"),
                new KeyValuePair<string, string>("P5","\"Time\".\"Calendar Date\""),
                new KeyValuePair<string, string>("P6",dateStr),
                new KeyValuePair<string, string>("P7","eq"),
                new KeyValuePair<string, string>("P8","\"Operation\".\"Store\""),
                new KeyValuePair<string, string>("P9",P9),               
                new KeyValuePair<string, string>("P10","eq"),
                new KeyValuePair<string, string>("P11","\"Base Measure\".\"After Ratio\""),
                new KeyValuePair<string, string>("P12","1 0.945")
            });
            return message;
        }

        /// <summary>
        /// 进入展示数据界面
        /// </summary>
        private HttpRequestMessage RequestSalesStep2(string dateStr)
        {
            var message = new HttpRequestMessage(HttpMethod.Post, "https://biee.mcdonalds.cn/analytics/saw.dll?PortalPages");
            message.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36");
            message.Content = new FormUrlEncodedContent(new[]
           {
                new KeyValuePair<string, string>("Page","R07.Daily Sales Rpt by Period And Store"),
                new KeyValuePair<string, string>("Action","Navigate"),
                new KeyValuePair<string, string>("PortalPath","/shared/Dashboard/_portal/Daily Sales"),
                new KeyValuePair<string, string>("P0","4"),
                new KeyValuePair<string, string>("P1","eq"),
                new KeyValuePair<string, string>("P2","\"Operation\".\"Store Key\""),               
                new KeyValuePair<string, string>("syndicate","siebel"),
                new KeyValuePair<string, string>("P3",P3),              
                new KeyValuePair<string, string>("P10","eq"),
                new KeyValuePair<string, string>("P4","bet"),
                new KeyValuePair<string, string>("P11","\"Base Measure\".\"After Ratio\""),
                new KeyValuePair<string, string>("P5","\"Time\".\"Calendar Date\""),
                new KeyValuePair<string, string>("P12","1 0.945"),
                new KeyValuePair<string, string>("P6",dateStr),
                new KeyValuePair<string, string>("P7","eq"),
                new KeyValuePair<string, string>("P8","\"Operation\".\"Store\""),              
                new KeyValuePair<string, string>("Options","dfr"),
                new KeyValuePair<string, string>("P9",P9)                    
            });
            return message;
        }

        /// <summary>
        /// 下载前准备
        /// </summary>
        private HttpRequestMessage RequestSalesStep3(string viewid, string sid, string viewstate, string xml)
        {
            var message = new HttpRequestMessage(HttpMethod.Post, "https://biee.mcdonalds.cn/analytics/saw.dll?Go");
            message.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36");
            DateTimeOffset now = DateTimeOffset.Now;
            string timestamp = now.ToUnixTimeMilliseconds().ToString();
            message.Content = new FormUrlEncodedContent(new[]
           {
                new KeyValuePair<string, string>("ViewID",viewid),
                new KeyValuePair<string, string>("Action","Download"),
                new KeyValuePair<string, string>("SearchID",sid),
                new KeyValuePair<string, string>("Style","blafp"),
                new KeyValuePair<string, string>("ViewState",viewstate),
                new KeyValuePair<string, string>("ItemName","R07.Daily Sales Rpt by Period"),
                new KeyValuePair<string, string>("path","/shared/Sales/R07.Daily Sales Rpt by Period"),
                new KeyValuePair<string, string>("Format","excel2007"),
                new KeyValuePair<string, string>("Extension",".xlsx"),
                new KeyValuePair<string, string>("DownloadId",timestamp),
                new KeyValuePair<string, string>("clientStateXml",xml)
            });
            return message;
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <returns></returns>
        private HttpRequestMessage RequestSalesStep4(string status)
        {
            var message = new HttpRequestMessage(HttpMethod.Get, $"https://biee.mcdonalds.cn/analytics/saw.dll?downloadExcelFile&d={status}&ItemName=R07.Daily Sales Rpt by Period And Store(DB)");
            return message;
        }

    }
}
